package com.cacho.s2b.lesson.grammar.func;

import com.cacho.s2b.lesson.vo.ApiTestInfo;

import java.text.ParseException;

public class GrammarFuncFormat implements GrammarFunc {
    public String getString(ApiTestInfo testInfo, String[] parts, int len) throws ParseException {
        FormatType type = FormatType.UPPER;
        int size = parts.length;
        if (size > 0) {
            type = parts[0].isEmpty() ? type : FormatType.valueOf(parts[0].toUpperCase());
        } else if (size < 1) {
            throw new ParseException("format expression must have at least 1 param", 0);
        }
        String temp = "";
        try {
            switch (type) {
                default -> temp = parts[1].trim();
                case UPPER -> {
                    if (size < 2) {
                        throw new Exception("Params number must be 2");
                    }
                    temp = parts[1].toUpperCase();
                }
                case LOWER -> {
                    if (size < 2) {
                        throw new Exception("Params number must be 2");
                    }
                    temp = parts[1].toLowerCase();
                }
                case SUBSTRING -> {
                    if (size < 3) {
                        throw new Exception("Params number must be 3 or 4");
                    }
                    if (size == 3){
                        temp = parts[1].trim().substring(Integer.parseInt(parts[2]));
                    } else if (size >= 4){
                        temp = parts[1].trim().substring(Integer.parseInt(parts[2]),Integer.parseInt(parts[3]));
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(
                    String.format("Format a string fail")
            );
        }
        return temp;

    }

    enum FormatType {
        UPPER(1, "返回全大写字符串。{{format(UPPER,Abcd123)}} 返回 ABCD123"),
        LOWER(2,"返回全小写字母。{{format(LOWER,Abc123)}} 返回 abc123"),
        SUBSTRING(3,"截取字符串。{{format(SUBSTRING,Abc123,1,3)}} 返回 bc");
        private final int value;
        private final String label;

        FormatType(int value, String label) {
            this.value = value;
            this.label = label;
        }

        public int getValue() {
            return value;
        }

        public String getLabel() {
            return label;
        }
    }
}
